<script setup>
import * as echarts from 'echarts'
import { onMounted, ref, onUnmounted, watch } from 'vue'

const chartRef = ref(null)
let myChart = null
let resizeObserver = null
onMounted(() => {
    if (chartRef.value) {
        myChart = echarts.init(chartRef.value)
        const option = {
            tooltip: {
                backgroundColor: 'rgba(37,41,56,.8)',
                borderColor: '#02a6b5',
                textStyle: {
                    color: '#fff'
                },
                formatter: function (params) {
                    return params.seriesName + '</br> ' + params.name + ': ' + params.value + ' (' + Math.round(params.percent) + '%)';
                }
            },
            legend: {
                bottom: '0%',
                left: '0%',
                textStyle: {
                    color: '#8589a5',   // 设置图例文字颜色
                    fontSize: 10
                }
            },
            series: [
                {
                    name: '年龄分布',
                    type: 'pie',
                    radius: ['45%', '65%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: false,
                        position: 'center'
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: 1, name: '0岁以上', itemStyle: { color: '#1089e7' } },
                        { value: 4, name: '20-29岁', itemStyle: { color: '#f57474' } },
                        { value: 2, name: '30-39岁', itemStyle: { color: '#56d0e3' } },
                        { value: 2, name: '40-49岁', itemStyle: { color: '#f8b448' } },
                        { value: 1, name: '50岁以上', itemStyle: { color: '#8b78f6' } }
                    ]
                }
            ]
        };
        myChart.setOption(option)
        if (window.ResizeObserver) {
            resizeObserver = new ResizeObserver(() => {
                myChart.resize()
            })
            resizeObserver.observe(chartRef.value)
        } else {
            window.addEventListener('resize', handleResize)
        }
    }
})
// 处理窗口大小变化
const handleResize = () => {
    if (myChart) {
        myChart.resize({
            animation: {
                duration: 300
            }
        })
    }
}

// 组件卸载时清理事件监听器
onUnmounted(() => {
    if (resizeObserver && chartRef.value) {
        resizeObserver.unobserve(chartRef.value)
        resizeObserver = null
    }

    window.removeEventListener('resize', handleResize)

    if (myChart) {
        myChart.dispose()
    }
})
</script>

<template>
    <div ref="chartRef" style="width: 100%; height: 240px;"></div>
</template>

<style lang="scss" scoped></style>
